<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="authStore.userInfo.username" disabled />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="authStore.userInfo.dept_name" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="authStore.userInfo.role" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="profileForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="isLoading">
            保存修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { ElMessage } from 'element-plus';

const authStore = useAuthStore();
const profileFormRef = ref(null);
const isLoading = ref(false);

const profileForm = reactive({
  name: '',
  email: '',
  phone: '',
});

const profileRules = {
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
};

onMounted(() => {
  if (authStore.userInfo) {
    profileForm.name = authStore.userInfo.name;
    profileForm.email = authStore.userInfo.email;
    profileForm.phone = authStore.userInfo.phone || '';
  }
});

const handleSubmit = async () => {
  if (!profileFormRef.value) return;
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      try {
        const result = await authStore.updateProfile({
          name: profileForm.name,
          email: profileForm.email,
          phone: profileForm.phone,
        });
        if (result.success) {
          ElMessage.success('个人资料更新成功');
        } else {
          ElMessage.error(result.message || '更新失败');
        }
      } catch (error) {
        ElMessage.error('更新个人资料时发生错误');
      } finally {
        isLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
}
.profile-card {
  max-width: 600px;
  margin: 0 auto;
}
</style>